Answers may be longer than I would deem sufficient on an exam. Some might vary slightly based on points of interest, examples, or personal experience. These suggested answers are designed to give you both the answer and a short explanation of why it is the answer.

The Popularity of Baby Names

Install and load the package babynames. Get help for ?babynames to see what the data includes.

library(tidyverse)
## ── Attaching packages ─────────────────────────────────────────────────────────────────────────── tidyverse 1.2.1 ──
## ✔ ggplot2 3.2.0     ✔ purrr   0.3.2
## ✔ tibble  2.1.3     ✔ dplyr   0.8.3
## ✔ tidyr   1.0.0     ✔ stringr 1.4.0
## ✔ readr   1.3.1     ✔ forcats 0.4.0
## ── Conflicts ────────────────────────────────────────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag()    masks stats::lag()
# install for first use
# install.packages("babynames")

# load package 
library(babynames)

# explore help
# ?babynames

Question 1

Part A

What are the top 5 boys names for 2017, and what percent of overall names is each?

# save as a new tibble
top_5_boys_2017 <- babynames %>% # take data
  filter(sex=="M", # filter by males
         year==2017) %>% # and for 2007
  arrange(desc(n)) %>% # arrange in largest-to-smallest order of n (number)
  slice(1:5) %>% # optional, look only at first 5 rows; head(., n=5) also works
  mutate(percent = round(prop*100, 2)) # also optional, make a percent variable rounded to 2 decimals

# look at our new tibble
top_5_boys_2017

The top 5 names are

  1. Liam (0.95%)
  2. Noah (0.93%)
  3. William (0.76%)
  4. James (0.72%)
  5. Logan (0.71%)

Part B

What are the top 5 girls names, and what percent of overall names is each?

# save as a new tibble
top_5_girls_2017 <- babynames %>% # take data
  filter(sex=="F", # filter by females
         year==2017) %>% # and for 2007
  arrange(desc(n)) %>% # arrange in largest-to-smallest order of n (number)
  slice(1:5) %>% # optional, look only at first 5 rows; head(., n=5) also works
  mutate(percent = round(prop*100, 2)) # also optional, make a percent variable rounded to 2 decimals

# look at our new tibble
top_5_girls_2017

The top 5 names are

  1. Emma (1.05%)
  2. Olivia (0.99%)
  3. Ava (0.85%)
  4. Isabella (0.81%)
  5. Sophia (0.79%)

Question 2

Make two barplots, of these top 5 names, one for each sex. Map aesthetics x to name and y to prop1 and use geom_col (since you are declaring a specific y, otherwise you could just use geom_bar() and just an x.)

ggplot(data = top_5_boys_2017)+
  aes(x = reorder(name, n), #note this reorders the x variable from small to large n
      y = percent, # you can use prop if you didn't make a percent variable
      fill = name)+ # optional color!
  geom_col()+
  
  # now I'm just making it pretty
  scale_y_continuous(labels=function(x)paste(x,"%",sep=""))+ # optional, add percent signs
      labs(x = "Name",
         y = "Percent of All Babies With Name",
         title = "Most Popular Boys Names Since 1880",
         fill = "Boy's Name",
         caption = "Source: SSA")+
    theme_classic(base_family = "Fira Sans Condensed", base_size=16)+
  coord_flip()+ # rotate axes!
  theme(legend.position = "") # hide legend

ggplot(data = top_5_girls_2017)+
  aes(x = reorder(name, n), #note this reorders the x variable from small to large n
      y = percent, # you can use prop if you didn't make a percent variable
      fill = name)+ # optional color!
  geom_col()+
  # now I'm just making it pretty
  scale_y_continuous(labels=function(x)paste(x,"%",sep=""))+ # optional, add percent signs
      labs(x = "Name",
         y = "Percent of All Girls With Name",
         title = "Most Popular Girls Names Since 1880",
         fill = "Girl's Name",
         caption = "Source: SSA")+
    theme_classic(base_family = "Fira Sans Condensed", base_size=16)+
  coord_flip()+ # rotate axes!
  theme(legend.position = "") # hide legend

Question 3

Find your name.2 count by sex how many babies since 1880 were named your name.3 Also add a variable for the percent of each sex.

babynames %>%
  filter(name == "Ryan") %>%
  count(sex, wt=n) %>%
  mutate(percent = round((n/sum(n)*100),2))

Question 4

Make a line graph of the number of babies with your name over time, colored by sex.

babynames %>%
  filter(name == "Ryan") %>%
  ggplot(data = .)+
  aes(x = year,
      y = n,
      color = sex)+
  geom_line(size=1)+
  labs(x = "Year",
       y = "Number of Babies",
       title = "Popularity of Babies Named 'Ryan'",
       color = "Sex",
       caption = "Source: SSA")+
    theme_classic(base_family = "Fira Sans Condensed", base_size=16)

Question 5

Part A

Make a table of the most common name for boys by year between 1980-2017.4

babynames %>%
  group_by(year) %>%
  filter(sex == "M",
         year>1980) %>%
  arrange(desc(n))%>%
  slice(1) # take first row only

Part B

Now do the same for girls.

babynames %>%
  group_by(year) %>%
  filter(sex == "F",
         year>1980) %>%
  arrange(desc(n))%>%
  slice(1) # take first row only

Question 6

Now let’s graph the evolution of the most common names since 1880. ### Part A First, find out what are the top 10 overall most popular names for boys and for girls. You may want to create two vectors, each with these top 5 names.

babynames %>%
  group_by(name) %>%
  filter(sex=="M") %>%
  summarize(total=sum(n)) %>%
  arrange(desc(total)) %>%
  slice(1:5)
# make a vector of the names (we'll need this for our graph below)
top_boys_names<-c("James", "John", "Robert", "Michael", "William")
babynames %>%
  group_by(name) %>%
  filter(sex=="F") %>%
  summarize(total=sum(n)) %>%
  arrange(desc(total)) %>%
  slice(1:5)
# make a vector of the names (we'll need this for our graph below)
top_girls_names<-c("Mary", "Elizabeth", "Patricia", "Jennifer", "Linda")

Part B

Now make two linegraphs of these 5 names over time, one for boys, and one for girls.

babynames %>%
  group_by(year) %>%
  filter(sex == "M",
         name %in% top_boys_names) %>%
  ggplot(data = .,
         aes(x = year,
             y = prop,
             color = name))+
  geom_line()+
      labs(x = "Year",
         y = "Proportion of Babies with Name",
         title = "Most Popular Boys Names Since 1880",
         color = "Boy's Name",
         caption = "Source: SSA")+
    theme_classic(base_family = "Fira Sans Condensed", base_size=16)

babynames %>%
  group_by(year) %>%
  filter(sex == "F",
         name %in% top_girls_names) %>%
  ggplot(data = .,
         aes(x = year,
             y = prop,
             color = name))+
  geom_line()+
    labs(x = "Year",
         y = "Proportion of Babies with Name",
         title = "Most Popular Girls Names Since 1880",
         color = "Girl's Name",
         caption = "Source: SSA")+
    theme_classic(base_family = "Fira Sans Condensed", base_size=16)

Question 7

Bonus (hard!): What are the 10 most common “gender-neutral” names?5

There’s a lot to this, so I’ll break this up step by step and show you what happens at each major step.

We want to find the names where 48% to 52% of the babies with the name are male, as I defined in the footnote. First let’s mutate a variable to figure out how many babies with a particular name are male.

To do this, we’ll need to make a two variables to count the number of males and females of each name each year. We’ll use the ifelse() function for each:

  1. Make a male variable where, for each name in each year, if sex=="M", then count the number of males (n) that year, otherwise set it equal to 0.
  2. Make a female variable where, for each name in each year, if sex=="F", then count the number of females (n) that year, otherwise set it equal to 0.
babynames %>%
  mutate(male = ifelse(sex == "M", n, 0),
         female = ifelse(sex == "F", n, 0))

Now with this variable, we want to count the total number of males and females with each name over the entire dataset. Let’s first group_by(name) so we’ll get one row for every name. We will summarize() and take the sum of our male and of our female variables.

babynames %>%
  mutate(male = ifelse(sex == "M", n, 0),
         female = ifelse(sex == "F", n, 0)) %>%
  group_by(name) %>%
    summarize(Male = sum(male),
              Female = sum(female))

Now, we want to figure out what fraction of each name is Male or Female. It doesn’t matter which we do here, I’ll do Male. mutate() a new variable I’ll call perc_male for the percent of the name being for Male babies. It takes the summed variables we made before, and takes the fraction that are Male, multiplying by 100 to get percents (which isn’t necessary, but is easy to read).

babynames %>%
  mutate(male = ifelse(sex == "M", n, 0),
         female = ifelse(sex == "F", n, 0)) %>%
  group_by(name) %>%
    summarize(Male = sum(male),
              Female = sum(female))%>%
  filter(Male!=0,
         Female!=0) %>%
  mutate(perc_male = (Male/(Male+Female)*100))

Right now, it’s still in alphabetical order. We want to arrange it by perc_male, and more importantly, we want perc_male to be between 48 and 52, so let’s filter accordingly:

babynames %>%
  mutate(male = ifelse(sex == "M", n, 0),
         female = ifelse(sex == "F", n, 0)) %>%
  group_by(name) %>%
    summarize(Male = sum(male),
              Female = sum(female))%>%
  mutate(perc_male = (Male/(Male+Female)*100)) %>%
  arrange(perc_male) %>%
  filter(perc_male > 48,
         perc_male < 52)

This gives us a lot of names, all falling between 48% and 52% male. But we want the most popular names that are in this range. So let’s finally mutate a new variable called total that simply adds the number of Male and Female babies with a name. Then let’s arrange our results by desc(total) to get the largest first, and then slice(1:10) to get the top 10 only.

babynames %>%
  mutate(male = ifelse(sex == "M", n, 0),
         female = ifelse(sex == "F", n, 0)) %>%
  group_by(name) %>%
    summarize(Male = sum(male),
              Female = sum(female))%>%
  mutate(perc_male = (Male/(Male+Female)*100)) %>%
  arrange(perc_male) %>%
  filter(perc_male > 48,
         perc_male < 52) %>%
  mutate(total = Male+Female) %>%
  arrange(desc(total)) %>%
  slice(1:10)

Political and Economic Freedom Around the World

For the remaining questions, we’ll look at the relationship between Economic Freedom and Political Freedom in countries around the world today. Our data for economic freedom comes from the Fraser Institute, and our data for political freedom comes from Freedom House.

Question 8

Download these two datasets that I’ve cleaned up a bit:6

Load them with df<-read_csv("name_of_the_file.csv") and save one as econfreedom and the other as polfreedom. Look at each tibble you’ve created.

I am creating this document for/from the website, so these are all stored in a folder called data, one folder up from my current folder, homeworks. To get there, I go up one folder (..) and move to data, where these csv files are stored.

I suggest you either keep the data in the same folder as your R working directory (always check with getwd()), or create an R Project and store the data files in that same folder.

# import data with read_csv from readr

# note these file paths will be different for you
polfreedom<-read_csv("../data/freedomhouse2018.csv")
## Parsed with column specification:
## cols(
##   .default = col_double(),
##   `Country/Territory` = col_character(),
##   Status = col_character()
## )
## See spec(...) for full column specifications.
econfreedom<-read_csv("../data/econfreedom.csv")
## Warning: Missing column names filled in: 'X1' [1]
## Parsed with column specification:
## cols(
##   X1 = col_double(),
##   Country = col_character(),
##   ISO = col_character(),
##   ef = col_double(),
##   gdp = col_double(),
##   continent = col_character()
## )
# look at each dataframe
polfreedom
econfreedom

Question 9

The polfreedom dataset is still a bit messy. Let’s overwrite it (or assign to something like polfreedom2) and select Country/Territory and Total (total freedom score) and rename Country.Territory to Country.

polfreedom<-polfreedom %>%
  select(`Country/Territory`, Total) %>%
  rename(Country=`Country/Territory`)

Question 10

Now we can try to merge these two datasets into one. Since they both have Country as a variable, we can merge these tibbles using left_join(econfreedom, polfreedom, by="Country")7 and save this as a new tibble (something like freedom).

This one is a bit advanced to explain (but see the last few slides of 1.5 for more), so just copy what I gave you!

freedom<-left_join(econfreedom, polfreedom, by="Country")

Question 11

Now make a scatterplot of Political Freedom (total)8 as y on Economic Freedom (ef) as x and color by continent.

## Warning: Removed 1 rows containing missing values (geom_point).

Question 12

Let’s do this again, but highlight some key countries. Pick three countries, and make a new tibble from freedom that is only the observations of those countries. Additionally, install and load a packaged called ggrepel9 Next, redo your plot from question 11, but now add a layer: geom_label_repel and set its data to your three-country tibble, use same aesthetics as your overall plot, but be sure to add label = ISO, to use the ISO country code to label.10

# install.packages("ggrepel") install for first use 
library(ggrepel) # load 

interest<-filter(freedom, ISO %in% c("CHN", "NOR", "USA"))

ggplot(data=freedom, aes(x=ef,y=Total))+
  geom_point(aes(color=continent))+
  geom_label_repel(data=interest, aes(ef, Total, label=ISO,color=continent),alpha=0.6)+
  xlab("Economic Freedom Score")+ylab("Political Freedom Score")+theme_bw()+labs(caption="Sources: Frasier Institute, Freedom House")+
  theme_classic(base_family = "Fira Sans Condensed", base_size=16)
## Warning: Removed 1 rows containing missing values (geom_point).

Question 13

Make another plot similar to 12, except this time use GDP per Capita (gdp) as y. Feel free to try to put a regression line with geom_smooth()!11. Those of you in my Development course, you just made my graphs from Lesson 2!

ggplot(data=freedom, aes(x=ef,y=gdp))+
  geom_point(aes(color=continent))+
  geom_smooth(data=freedom)+
  geom_label_repel(data=interest, aes(ef, Total, label=ISO,color=continent),alpha=0.6)+
  xlab("Economic Freedom Score")+ylab("Political Freedom Score")+theme_bw()+labs(caption="Sources: Frasier Institute, Freedom House")+
  theme_classic(base_family = "Fira Sans Condensed", base_size=16)
## `geom_smooth()` using method = 'loess' and formula 'y ~ x'


  1. Or percent, if you made that variable, as I did.↩︎

  2. If your name isn’t in there :(, pick a random name.↩︎

  3. Hint: if you do this, you’ll get the number of rows (years) there are in the data. You want to add the number of babies in each row (n), so inside count, add wt=n to weight the count by n.↩︎

  4. Hint: once you’ve got all the right conditions, you’ll get a table with a lot of data. You only want to slice the 1st row for each table.↩︎

  5. This is hard to define. For our purposes, let’s define this as names where between 48 and 52% of the babies with the name are Male.↩︎

  6. If you want, try downloading them from the websites yourself!↩︎

  7. Note, if you saved as something else in question 9., use that instead of polfreedom!↩︎

  8. Feel free to rename these!↩︎

  9. This automatically adjusts labels so they don’t cover points on a plot!↩︎

  10. You might also want to set a low alpha level to make sure the labels don’t obscure other points!↩︎

  11. If you do, be sure to set its data to the full freedom, not just your three countries!↩︎